#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 数据来源: https://github.com/selva86/datasets

import pandas as pd
import numpy as np 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
import seaborn as sns 
import warnings; warnings.filterwarnings(action='once')

# 1.4 偏差(Deviation)
# 1.4.1 发散型条形图(Diverging Bars)
# 根据单个指标查看项目的变化情况,并可视化此差异的顺序和数量,
# 散型条形图有助于快速区分数据中组的性能,并且非常直观.
"""
# Prepare Data
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mtcars.csv")
x = df.loc[:,['mpg']]
df['mpg_z'] = (x - x.mean())/ x.std()
df['colors'] = ['red' if x < 0 else 'green' for x in df['mpg_z']]
df.sort_values('mpg_z',inplace=True)
df.reset_index(inplace=True)

# Draw plot
plt.figure(figsize=(14,10),dpi=80)
plt.hlines(y=df.index,xmin=0,xmax=df.mpg_z,color=df.colors, alpha=0.4,linewidth=5)

# Decorations
plt.gca().set(ylabel='$Model$',xlabel='$Mileage$')
plt.yticks(df.index,df.cars, fontsize=12)
plt.title('Diverging Bars of Car Mileage',fontdict={'size': 20})
plt.grid(linestyle='--',alpha=0.5)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\DivergingBars.png")
plt.show()
"""



# 1.4.2 发散型文本(Diverging Texts)
# 发散型文本(Diverging Texts)与发散型条形图(Diverging Bars)相似,
# 以一种漂亮和可呈现的方式显示图表中每个项目的价值,使用这种方法.
"""
# Prepare Data
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mtcars.csv")
x = df.loc[:,['mpg']]
df['mpg_z'] = (x - x.mean())/x.std()
df['colors'] = ['red' if x < 0 else 'green' for x in df['mpg_z']]
df.sort_values('mpg_z',inplace=True)
df.reset_index(inplace=True)

# Draw plot
plt.figure(figsize=(14,14),dpi=80)
plt.hlines(y=df.index,xmin=0,xmax=df.mpg_z)
for x, y, tex in zip(df.mpg_z,df.index,df.mpg_z):
    t = plt.text(x,y, round(tex,2), horizontalalignment='right' if x < 0 else 'left',\
            verticalalignment='center',fontdict={'color':'red' if x < 0 else 'green', 'size':14})

# Decorations
plt.yticks(df.index, df.cars,fontsize=12)
plt.title('Diverging Text Bars of Car Mileage',fontdict={'size': 20})
plt.grid(linestyle='--',alpha=0.5)
plt.xlim(-2.5,2.5)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\DivergingTexts.png")
plt.show()
"""



# 1.4.3 发散型包点图(Diverging Dot Plot)
# 发散型包点图(Diverging Dot Plot)。与发散型条形图相比,条的缺失减少了组之间的对比度和差异.
"""
# Prepare Data
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mtcars.csv")
x = df.loc[:,['mpg']]
df['mpg_z'] = (x - x.mean())/x.std()
df['colors'] = ['red' if x < 0 else 'darkgreen' for x in df['mpg_z']]
df.sort_values('mpg_z',inplace=True)
df.reset_index(inplace=True)

# Draw plot
plt.figure(figsize=(14,16),dpi=80)
plt.scatter(df.mpg_z,df.index,s=450, alpha=.6, color=df.colors)
for x, y, tex in zip(df.mpg_z,df.index,df.mpg_z):
    t = plt.text(x,y, round(tex,1),horizontalalignment='center',verticalalignment='center', fontdict={'color':'white'})

# Decorations
# Lighten borders
plt.gca().spines["top"].set_alpha(.3)
plt.gca().spines["bottom"].set_alpha(.3)
plt.gca().spines["right"].set_alpha(.3)
plt.gca().spines["left"].set_alpha(.3)

plt.yticks(df.index,df.cars)
plt.title('Diverging Dotplot of Car Mileage',fontdict={'size':20})
plt.xlabel('$Mileage$')
plt.grid(linestyle='--',alpha=0.5)
plt.xlim(-2.5,2.5)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\DivergingDotPlot.png")
plt.show()
"""



# 1.4.4 带标记的发散型棒棒糖图(Diverging Lollipop Chart with Markers)
# 带标记的棒棒糖图通过强调您想要引起注意的任何重要数据点并在图表中适当地给出推理.提供了一种对差异进行可视化的灵活方式.
df = pd.read_csv("F:\\PythonProject\\data\\fromdata\\datasets\\mtcars.csv")
x = df.loc[:,['mpg']]
df['mpg_z'] = (x - x.mean())/x.std()
df['colors'] = 'black'

# color fiat differently
df.loc[df.cars == 'Fiat X1-9','colors'] = 'darkorange'
df.sort_values('mpg_z',inplace=True)
df.reset_index(inplace=True)

# Draw plot
import matplotlib.patches as patches

plt.figure(figsize=(14,16),dpi=80)
plt.hlines(y=df.index,xmin=0,xmax=df.mpg_z,color=df.colors,alpha=0.4,linewidth=1)
plt.scatter(df.mpg_z,df.index,color=df.colors, s=[600 if x == 'Fiat X1-9' else 300 for x in df.cars],alpha=0.6)
plt.yticks(df.index,df.cars)
plt.xticks(fontsize=12)

# Annotate
plt.annotate('Mercedes Models',xy=(0.0,11.0),xytext=(1.0,11),xycoords='data',\
    fontsize=15,ha='center',va='center',\
    bbox=dict(boxstyle='square',fc='firebrick'),
    arrowprops=dict(arrowstyle='-[,widthB=2.0,lengthB=1.5',lw=2.0,color='steelblue'),color='white')

# Add Patches
p1 = patches.Rectangle((-2.0,-1),width=.3,height=3,alpha=.2,facecolor='red')
p2 = patches.Rectangle((1.5,27),width=.8,height=5,alpha=.2,facecolor='green')
plt.gca().add_patch(p1)
plt.gca().add_patch(p2)

# Decorate
plt.title('Diverging Bars of Car Mileage',fontdict={'size':20})
plt.grid(linestyle='--',alpha=0.5)
plt.savefig("F:\\PythonProject\\AI\\Python\\DataAnalysis\\scripts\\files\\DivergingLollipopChart.png")
plt.show()
